﻿using System;
using System.Linq;
using System.Windows.Forms;
using Microsoft.WindowsMobile.PocketOutlook;
using SenseTimeTracker.Main;
using SenseTimeTracker.Misc;
using SenseTimeTracker.Properties;
using StedySoft.SenseSDK;
using StedySoft.SenseSDK.DrawingCE;
using Task=SenseTimeTracker.BusinessLayer.Task;

namespace SenseTimeTracker.Tasks
{
	/// <summary>
	/// Class implements the task slider panel
	/// </summary>
	public class TasksSliderPanel : CommonSliderPanel<Task>
	{
		private MenuItem outlookMenuItem;
		private MenuItem exportOutlookMenuItem;
		private MenuItem importOutlookMenuItem;

		/// <summary>
		/// Initializes a new instance of the <see cref="TasksSliderPanel"/> class.
		/// </summary>
		/// <param name="form">The form the panel is contained on.</param>
		public TasksSliderPanel(SenseTimeTrackerForm form)
			: base(form, "TaskSmallIcon.png", "TaskLargeIcon.png", MenuEnty.All & ~MenuEnty.Duplicate)
		{
			sorting = Persistance.Instance.TasksSorting;
			sortColumns = SortColumn.Name | SortColumn.Type | SortColumn.Number;
			
			outlookMenuItem = new MenuItem();
			outlookMenuItem.Text = Resources.MenuItemOutlook;
			menuItem.MenuItems.Add(outlookMenuItem);

			exportOutlookMenuItem = new MenuItem();
			exportOutlookMenuItem.Text = Resources.MenuItemExport;
			outlookMenuItem.MenuItems.Add(exportOutlookMenuItem);

			importOutlookMenuItem = new MenuItem();
			importOutlookMenuItem.Text = Resources.MenuItemImport;
			outlookMenuItem.MenuItems.Add(importOutlookMenuItem);
		}

		void exportTaskMenuItem_Click(object sender, EventArgs e)
		{
			OutlookSession o = new OutlookSession();
			Microsoft.WindowsMobile.PocketOutlook.Task task = new Microsoft.WindowsMobile.PocketOutlook.Task();
			task.Subject = "ttttt";
			task.Body = "Hallo";
			o.Tasks.Items.Add(task);
			task = o.Tasks.Items[3];
			int z = 0;
		}

		/// <summary>
		/// Gets the name of the panel.
		/// </summary>
		public override string Name
		{
			get { return Resources.PanelTasksName; }
		}

		/// <summary>
		/// Handles new task menu item click event
		/// </summary>
		/// <param name="sender">The sender of the event.</param>
		/// <param name="e">The event arguments.</param>
		protected override void MenuItemNewEntry_Click(object sender, EventArgs e)
		{
			using (new DialogHelper(ownedForm))
			{
				TaskEditForm form = new TaskEditForm
      	{
					Task = new Task(),
      	};

				if (form.ShowDialog() == DialogResult.OK)
				{
					form.Task.Insert();
					Bind(senseListControl);
				}
			}
		}

		/// <summary>
		/// Handles edit task menu item click event
		/// </summary>
		/// <param name="sender">The sender of the object.</param>
		/// <param name="e">The event arguments.</param>
		protected override void MenuItemEditEntry_Click(object sender, EventArgs e)
		{
			TaskDisplayItem item = senseListControl.FocusedItem as TaskDisplayItem;
			if (item != null)
			{
				EditTask(item.Task.Id);
				Bind(senseListControl);
			}
		}

		protected override void MenuItemCopyEntry_Click(object sender, EventArgs e)
		{
			TaskDisplayItem item = senseListControl.FocusedItem as TaskDisplayItem;
			if (item != null)
			{
				Guid newTaskId = DatabaseManager.TaskCopy(item.Task.Id, null);
				if (!EditTask(newTaskId))
				{
					Task.Delete(newTaskId);
				}

				Bind(senseListControl);
			}
		}

		protected override void MenuItemRemoveEntry_Click(object sender, EventArgs e)
		{
			if (SenseAPIs.SenseMessageBox.Show(Resources.DialogDeleteQuestion, Resources.DialogHeaderRemoveTask, SenseMessageBoxButtons.YesNo) == DialogResult.Yes)
			{
				TaskDisplayItem item = senseListControl.FocusedItem as TaskDisplayItem;
				if (item != null)
				{
					Task.Delete(item.Task.Id);
					Bind(senseListControl);
				}
			}
		}

		/// <summary>
		/// Binds the items to the list control
		/// </summary>
		/// <param name="senseListControl">
		/// The sense list control.
		/// </param>
		public override void Bind(SenseListControl senseListControl)
		{
			base.Bind(senseListControl);
			filterItem.PrimaryText = string.Format(
        "{0}: {1}, {2}: {3}",
				Resources.ClientLabel,
				DatabaseManager.ClientName(Persistance.Instance.FilterForTasks.ClientFilter),
				Resources.ProjectLabel,
				DatabaseManager.ProjectName(Persistance.Instance.FilterForTasks.ProjectFilter));
			senseListControl.AddItem(new SensePanelDividerItem(string.Empty, Resources.TasksExplanation));

			var filteredTasks = from task in Task.Tasks select task;
			if (Persistance.Instance.FilterForTasks.ClientFilter != DatabaseManager.AllClientsId)
			{
				filteredTasks = from task in filteredTasks where task.Client == Persistance.Instance.FilterForTasks.ClientFilter select task;
			}

			if (Persistance.Instance.FilterForTasks.ProjectFilter != DatabaseManager.AllProjectsId)
			{
				filteredTasks = from task in filteredTasks where task.Project == Persistance.Instance.FilterForTasks.ProjectFilter select task;
			}

			if (!Persistance.Instance.FilterForTasks.DisplayFinishedTasks)
			{
				filteredTasks = from task in filteredTasks where !task.Completed select task;
			}

			SortFilter(ref filteredTasks);
			foreach (Task task in filteredTasks)
			{
				senseListControl.AddItem(new TaskDisplayItem
				{
					Task = task,
				});
			}
		}

		public override void BindFilter()
		{
			SensePanelComboItem clientFilterComboBox = new SensePanelComboItem();
			clientFilterComboBox.LabelText = string.Format("{0}:", Resources.ClientLabel);
			clientFilterComboBox.ShowSeparator = true;
			Binder.BindCombobox(clientFilterComboBox.Items, Guid.Empty, Guid.Empty, true, false);
			clientFilterComboBox.SelectedValue = Persistance.Instance.FilterForTasks.ClientFilter;
			clientFilterComboBox.OnSelectedValueChanged += clientFilterComboBox_OnSelectedValueChanged;
			if (clientFilterComboBox.SelectedIndex == -1)
			{
				clientFilterComboBox.SelectedIndex = 0;
				Persistance.Instance.FilterForTasks.ClientFilter = (Guid)clientFilterComboBox.Items[0].Value;
			}

			SensePanelComboItem projectFilterComboBox = new SensePanelComboItem();
			projectFilterComboBox.LabelText = string.Format("{0}:", Resources.ProjectLabel); ;
			projectFilterComboBox.ShowSeparator = true;
			Binder.BindCombobox(projectFilterComboBox.Items, (Guid)clientFilterComboBox.SelectedValue, Guid.Empty, true, false);
			projectFilterComboBox.SelectedValue = Persistance.Instance.FilterForTasks.ProjectFilter;
			projectFilterComboBox.OnSelectedValueChanged += projectFilterComboBox_OnSelectedValueChanged;
			if (projectFilterComboBox.SelectedIndex == -1)
			{
				projectFilterComboBox.SelectedIndex = 0;
				Persistance.Instance.FilterForTasks.ProjectFilter = (Guid)projectFilterComboBox.Items[0].Value;
			}

			SensePanelCheckboxItem displayFinishedTasksCheckBox = new SensePanelCheckboxItem();
			displayFinishedTasksCheckBox.PrimaryText = Resources.DisplayFinishedTasks;
			displayFinishedTasksCheckBox.Status = Persistance.Instance.FilterForTasks.DisplayFinishedTasks ? ItemStatus.On : ItemStatus.Off;
			displayFinishedTasksCheckBox.OnStatusChanged += displayFinishedTasksCheckBox_OnStatusChanged;

			BindFilter(new SenseListControl.ISenseListItem[] { clientFilterComboBox, projectFilterComboBox, displayFinishedTasksCheckBox }, Resources.TasksFilterHeader);
		}

		void displayFinishedTasksCheckBox_OnStatusChanged(object Sender, ItemStatus Status)
		{
			Persistance.Instance.FilterForTasks.DisplayFinishedTasks = Status == ItemStatus.On;
			Persistance.Instance.Serialize();
		}

		void clientFilterComboBox_OnSelectedValueChanged(object Sender, object Value)
		{
			Persistance.Instance.FilterForTasks.ClientFilter = (Guid)Value;
			Persistance.Instance.Serialize();
			BindFilter();
		}

		void projectFilterComboBox_OnSelectedValueChanged(object Sender, object Value)
		{
			Persistance.Instance.Serialize();
			Persistance.Instance.FilterForTasks.ProjectFilter = (Guid)Value;
		}

		/// <summary>
		/// Edits a task
		/// </summary>
		/// <param name="taskId">Id of the task to be edited</param>
		/// <returns>True, if edited succesful</returns>
		private bool EditTask(Guid taskId)
		{
			using (new DialogHelper(ownedForm))
			{
				TaskEditForm form = new TaskEditForm
				{
					Task = Task.GetTask(taskId),
				};

				if (form.ShowDialog() == DialogResult.OK)
				{
					form.Task.Update();
					return true;
				}
			}

			return false;
		}
	}
}
